package it.fflabs.dynscript.test.client;

import it.fflabs.dynscript.client.JsClient;
import it.fflabs.dynscript.client.handler.IJsCallBack;
import it.fflabs.dynscript.client.handler.JsHandler;
import it.fflabs.dynscript.client.model.JsData;
import it.fflabs.dynscript.client.validation.IJsValidator;
import it.fflabs.dynscript.client.validation.exception.JsValidationException;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * <b>gwt-dynScript-test : Gwt_dynScript_test</b><br>
 * <hr>
 * Comment: This is a slightly modified version of the auto-generated GWT
 * example app's entry point. The purpose is to show how to use the
 * gwt-dynScript library<br>
 * <hr>
 * 09/feb/2012<br>
 * 
 * @author Francesco Foresti
 * 
 */
public class Gwt_dynScript_test implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while " + "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	// add this to your address bar along with the ip of the test service (if
	// it's not at the same ip of the test client)
	private static final String SERVICE_URL_KEY = "service";
	private String serviceUrl;

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button sendButton = new Button("Greet Remote Server");
		final Label errorLabel = new Label();

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {

			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				callServer();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					callServer();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a
			 * response.
			 */
			private void callServer() {
				try {
					errorLabel.setText("");

					sendButton.setEnabled(false);
					serverResponseLabel.setText("");

					JsHandler handler = new JsHandler(new IJsCallBack() {

						@Override
						public void onSuccess(JavaScriptObject jso) {
							dialogBox.setText("DynScript GET Call");
							serverResponseLabel.removeStyleName("serverResponseLabelError");

							// you have to know the structure of the returned
							// JSON.
							TestObject asT = TestObject.as(jso);
							serverResponseLabel.setHTML("<div>" + TestObject.value(asT) + "</div>");

							dialogBox.center();
							closeButton.setFocus(true);
						}

						@Override
						public void onTimeout() {
							Window.alert("the request timed out");
						}
					}, new IJsValidator() {

						@Override
						public void validate(JavaScriptObject jso) throws JsValidationException {
							closeButton.setFocus(true);
							if (jso == null) {
								throw new JsValidationException("returned object failed to validate");
							}
						}
					});

					serviceUrl = "http://" + retrieveServiceUrl(SERVICE_URL_KEY) + ":8080/testService";
					JsClient.doGet(serviceUrl, handler, 60000);

				} catch (Exception e) {
					// on validation failure
					dialogBox.setText("Remote Procedure Call - Failure");
					serverResponseLabel.addStyleName("serverResponseLabelError");
					serverResponseLabel.setHTML(SERVER_ERROR);
					dialogBox.center();
					closeButton.setFocus(true);
				}
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
	}

	/**
	 * found at http://www.netlobo.com/url_query_string_javascript.html
	 * 
	 * @return the value of the url parameter at the given key;
	 */
	public static native String retrieveServiceUrl(String key) /*-{
		var name = key;
		name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
		var regexS = "[\\?&]" + name + "=([^&#]*)";
		var regex = new RegExp(regexS);
		var results = regex.exec($wnd.location.href);
		if (results == null)
			return "127.0.0.1";
		else
			return results[1];
	}-*/;

	/**
	 * <b>gwt-dynScript-test : TestObject</b><br>
	 * <hr>
	 * Comment: this object is very similar to the one returned by the service.
	 * However, to get the value we're interest in we must use jsni<br>
	 * <hr>
	 * 09/feb/2012<br>
	 * 
	 * @author Francesco Foresti
	 * 
	 */
	public static class TestObject extends JsData<TestObject> {

		protected TestObject() {
		}

		public static native String value(TestObject tso) /*-{
															// will handle both strings and numeric types
															return "" + (tso.value + tso.anotherValue);
															}-*/;

	}
}
